import axios from 'axios'
// import Qs from 'qs'
import {ENV} from '../env_utils/getEnvInfo'
import urls from './urls/url'
import {dataFormat} from './format/index'
import { Message } from 'element-ui'
const instance = axios.create({
  baseURL: ENV.INFO_ENV.baseUrl,
  timeout: 3000
})
// POST传参序列化(添加请求拦截器)
instance.interceptors.request.use(config => {
  // TODO 后期token认真在这里做
  return config
}, error => { return Promise.reject(error.data.error.message) })
// 返回状态判断(添加响应拦截器)
instance.interceptors.response.use(res => {
  return res;
}, error => { return Promise.reject(error) })

const https = {get: {}, put: {}, delete: {}, post: {}}
for (let method in urls) {
  let types = urls[method]
  for (let key in types) {
    let url = types[key]
    https[method][key] = function (params = {}, context) {
      let realUrl = url.replace(/{(.+?)}/g, (match, key) => context[key.trim()])
      console.log('请求参数', method, key, realUrl, params, context)
      return instance[method](realUrl, params).then((res)=>{
        console.log('请求参数222', method, key, realUrl, params, context)
          let typesMap = dataFormat[method]
        if (typesMap) {
          let formatFunc = typesMap[key]
          if (formatFunc) {
            return [formatFunc(res.data)]
          }
        } else {
          console.error(`未建立${key}解析类`, method)
        }
        return [res, null];
      }).catch(error => {
        console.error("网络请求错误",error);
        Message.error(error.response.statusText + ':' + error.response.status)
        return [null, error]
      })
    }
  }
}
window._https = https
